package com.starinside.wp.service.impl;

import com.google.common.collect.ImmutableMap;
import com.starinside.wp.components.MemVerificationCache;
import com.starinside.wp.domain.AppUser;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.repository.AppUserRepository;
import com.starinside.wp.repository.WxUserRepository;
import com.starinside.wp.service.AppUserService;
import com.starinside.wp.service.BindedBabyService;
import com.starinside.wp.service.ChildrenService;
import com.starinside.wp.utils.MapConvertUtil;
import com.starinside.wp.utils.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.starinside.wp.foundation.constant.CommonConstant.Platform.WXMP;

/**
 * *******************************
 * Created by Tim.
 * form com.matt
 * on 2018/10/31
 * *******************************
 */
@Service
@Slf4j
public class AppUserServiceImpl implements AppUserService {

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    private AppUserRepository appUserRepository;

    @Autowired
    private MemVerificationCache cache;

    @Autowired
    WxUserRepository userRepository;

    @Autowired
    private BindedBabyService bindedBabyService;

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public AppUser selectByPhone(String phone) {
        return appUserRepository.findByPhone(phone);
    }

    @Override
    public AppUser save(AppUser user) {
        return appUserRepository.save(user);
    }

    @Override
    @Transactional
    public Map login(String mobile, String password) {
        Optional<WxUser> uo = userRepository.findByParentMobileAndSourceAppId(mobile,"888888");
        WxUser user = null;

        //关联父母对象
        AppUser au = selectByPhone(mobile);
        if (Objects.isNull(au)){
            throw new BusinessException(ErrorCode.PASSWORD_ERROR, "账号不存在！");
        }
        if (Objects.isNull(au.getExtension()) || StringUtils.equals(au.getExtension(),"")){
            au.setExtension(PasswordUtil.createOrderNo());
        }
        if (Objects.isNull(au.getPassword())){
            password = PasswordUtil.encode("123456").toLowerCase();
            au.setPassword(PasswordUtil.encode(mobile + password + au.getExtension()));
        }else {
            password =  password.toLowerCase();
        }

        String psw1 = PasswordUtil.encode(mobile + password + au.getExtension());

        if (!StringUtils.equals(au.getPassword(), psw1)) {
            throw new BusinessException(ErrorCode.PASSWORD_ERROR, "密码或账号错误！");
        }
        //设置默认宝宝
        List<BindedBabyVO> babies = bindedBabyService.getAllBindedBaby(mobile);

        if (!uo.isPresent()){
            user = new WxUser();
            //传个空字符除非唯一索引
            user.setOpenidWp(" ");
            user.setParentMobile(mobile);
            user.setSourceAppId("888888");
            if (babies == null || babies.size() == 0){
                throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "该家长没有宝宝");
            }
            user.setDefaultBaby(babies.get(0));
            user.setDefaultBabyId(babies.get(0).getId());

            user.setParentId(au.getId());
            au.setPassword(psw1);

            userRepository.save(user);
        }else{
            user = uo.get();
        }
        save(au);
        String ticket = cache.produceTicket(user.getId(), WXMP.codeOf());
        user.setTicket(ticket);
        Map data = MapConvertUtil.obejctToMap(user);

        data.put("ticket", ticket );

        int count = 0 ;
        for (int i = 0; i < babies.size(); i++) {
            if (babies.get(i).getStatus() !=1 ){
                count++;
            }
        }
        if (count == babies.size()){
            throw new BusinessException(ErrorCode.CHILDREN_NOT_EXIST, "该家长宝宝已毕学或没有宝宝！");
        }
        return data;
    }

//    @Override
//    public Object create(AppUser appUser) {
//        AppUser parentUser = appUserRepository.findByPhone(appUser.getPhone());
//        if (Objects.isNull(parentUser))
//            parentUser = AppUser.of_now(appUser.getName(), appUser.getPhone(), appUser.getCompany(),appUser.getPassword());
//        else {
//            parentUser.setCompany(appUser.getCompany());
//            parentUser.setName(appUser.getName());
//            parentUser.setPassword(appUser.getPassword());
//            parentUser.setPhone(appUser.getPhone());
//        }
//
//        //创建相应联系人
//        parentUser = appUserRepository.save(parentUser);
//        return parentUser;
//    }
}
